import { CacheService } from '@app/cache';
import { ConfigureService } from '@app/configure';
import { WechatService } from '@app/wechat';
import { Injectable, OnModuleInit } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class ScheduleService implements OnModuleInit{
    constructor(
        private readonly wechat:WechatService,
        private readonly config:ConfigureService,
        private readonly cache:CacheService
    ) {}

	onModuleInit() {
		this.getWxAccessToken()
	}

    @Cron('0 * * * *')
    public wxAccessToken() {
        console.log((new Date()).toLocaleTimeString())
        this.getWxAccessToken()
    }


	private async getWxAccessToken() {
        const r = await this.cache.client.ttl(this.config.get('wxAccessTokenKey'))
        console.log(r)
        if(r > (60 * 60 + 100)) return
        this.wechat.getWXAccessToken().then(token => {
            if(token != null) {
                this.cache.set(this.config.get('wxAccessTokenKey'), token, 2 * 60 * 60)
            }
        })
    }

}
